package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.service.UserSeriver;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class UserSeriverImpl implements UserSeriver {
    @Override
    public PageInfo<User> findAll(int currentPage, int pageSize) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        //1. 查询之前, 设置分页参数
        PageHelper.startPage(currentPage,pageSize);
        List<User> users = mapper.findAll();

        //2. 封装PageInfo<User>对象
        PageInfo<User> pageInfo = new PageInfo<>(users);
        sqlSession.close();
        return pageInfo;
    }

    @Override
    public void save(User user) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.save(user);
        sqlSession.close();
    }

    @Override
    public void deleteById(String id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.deleteById(id);
        sqlSession.close();
    }

    @Override
    public User findById(String id) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        User user = mapper.findById(id);
        sqlSession.close();
        return user;
    }

    @Override
    public void update(User user) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.update(user);
        sqlSession.close();
    }

    @Override
    public User login(User user) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);
        User u = dao.login(user.getUsername(), user.getPassword());
        sqlSession.close();
        return u;

    }

    @Override
    public void deleteAll(String[] ids) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        mapper.deleteAll(ids);
        sqlSession.close();
    }

    public int findByName(String name) {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        return mapper.findByName(name);
    }
}
